
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>spring上下文工具类 | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="众所周知,spring是目前来说最好的java框架,使用spring开发程序省去了我们很多繁杂的工作,比如说自己管理bean声明周期,依赖注入等。 我们平时除了依赖框架开发之外,spring同时提供了一些接口供开发者使用,这样的话我们的自己的程序就可以交给spring容器管理, 或者说使用spring的很多功能,常见的ApplicationContext和InitialingBean等,接下来将简">
<meta name="keywords" content="spring上下文工具类">
<meta property="og:type" content="article">
<meta property="og:title" content="spring上下文工具类">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2017/08/28/spring上下文工具类/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="众所周知,spring是目前来说最好的java框架,使用spring开发程序省去了我们很多繁杂的工作,比如说自己管理bean声明周期,依赖注入等。 我们平时除了依赖框架开发之外,spring同时提供了一些接口供开发者使用,这样的话我们的自己的程序就可以交给spring容器管理, 或者说使用spring的很多功能,常见的ApplicationContext和InitialingBean等,接下来将简">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/28/spring上下文工具类/1.png">
<meta property="og:updated_time" content="2017-08-28T09:20:36.580Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring上下文工具类">
<meta name="twitter:description" content="众所周知,spring是目前来说最好的java框架,使用spring开发程序省去了我们很多繁杂的工作,比如说自己管理bean声明周期,依赖注入等。 我们平时除了依赖框架开发之外,spring同时提供了一些接口供开发者使用,这样的话我们的自己的程序就可以交给spring容器管理, 或者说使用spring的很多功能,常见的ApplicationContext和InitialingBean等,接下来将简">
<meta name="twitter:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/28/spring上下文工具类/1.png">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2017/08/28/spring上下文工具类/" title="spring上下文工具类" itemprop="url">spring上下文工具类</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2017-08-28T09:15:23.000Z" itemprop="datePublished"> Published 2017-08-28</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、概念描述"><span class="toc-number">1.</span> <span class="toc-text">一、概念描述</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、创建maven项目-amp-添加基本依赖"><span class="toc-number">2.</span> <span class="toc-text">二、创建maven项目&添加基本依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写上下文工具类并注册到spring容器"><span class="toc-number">3.</span> <span class="toc-text">三、编写上下文工具类并注册到spring容器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、编写供上下文工具类操作的bean并注入spring容器"><span class="toc-number">4.</span> <span class="toc-text">四、编写供上下文工具类操作的bean并注入spring容器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#五、编写单元测试"><span class="toc-number">5.</span> <span class="toc-text">五、编写单元测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol>
		
		</div>
		
		<pre><code>众所周知,spring是目前来说最好的java框架,使用spring开发程序省去了我们很多繁杂的工作,比如说自己管理bean声明周期,依赖注入等。
我们平时除了依赖框架开发之外,spring同时提供了一些接口供开发者使用,这样的话我们的自己的程序就可以交给spring容器管理,
或者说使用spring的很多功能,常见的ApplicationContext和InitialingBean等,接下来将简单介绍ApplicationContext的应用场景和使用姿势:
</code></pre><a id="more"></a>    
<h5 id="一、概念描述"><a href="#一、概念描述" class="headerlink" title="一、概念描述"></a>一、概念描述</h5><pre><code>源码:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div></pre></td><td class="code"><pre><div class="line">/*</div><div class="line"> * Copyright 2002-2012 the original author or authors.</div><div class="line"> *</div><div class="line"> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</div><div class="line"> * you may not use this file except in compliance with the License.</div><div class="line"> * You may obtain a copy of the License at</div><div class="line"> *</div><div class="line"> *      http://www.apache.org/licenses/LICENSE-2.0</div><div class="line"> *</div><div class="line"> * Unless required by applicable law or agreed to in writing, software</div><div class="line"> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</div><div class="line"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</div><div class="line"> * See the License for the specific language governing permissions and</div><div class="line"> * limitations under the License.</div><div class="line"> */</div><div class="line"></div><div class="line">package org.springframework.context;</div><div class="line"></div><div class="line">import org.springframework.beans.BeansException;</div><div class="line">import org.springframework.beans.factory.Aware;</div><div class="line"></div><div class="line">/**</div><div class="line"> * Interface to be implemented by any object that wishes to be notified</div><div class="line"> * of the &#123;@link ApplicationContext&#125; that it runs in.</div><div class="line"> *</div><div class="line"> * &lt;p&gt;Implementing this interface makes sense for example when an object</div><div class="line"> * requires access to a set of collaborating beans. Note that configuration</div><div class="line"> * via bean references is preferable to implementing this interface just</div><div class="line"> * for bean lookup purposes.</div><div class="line"> *</div><div class="line"> * &lt;p&gt;This interface can also be implemented if an object needs access to file</div><div class="line"> * resources, i.e. wants to call &#123;@code getResource&#125;, wants to publish</div><div class="line"> * an application event, or requires access to the MessageSource. However,</div><div class="line"> * it is preferable to implement the more specific &#123;@link ResourceLoaderAware&#125;,</div><div class="line"> * &#123;@link ApplicationEventPublisherAware&#125; or &#123;@link MessageSourceAware&#125; interface</div><div class="line"> * in such a specific scenario.</div><div class="line"> *</div><div class="line"> * &lt;p&gt;Note that file resource dependencies can also be exposed as bean properties</div><div class="line"> * of type &#123;@link org.springframework.core.io.Resource&#125;, populated via Strings</div><div class="line"> * with automatic type conversion by the bean factory. This removes the need</div><div class="line"> * for implementing any callback interface just for the purpose of accessing</div><div class="line"> * a specific file resource.</div><div class="line"> *</div><div class="line"> * &lt;p&gt;&#123;@link org.springframework.context.support.ApplicationObjectSupport&#125; is a</div><div class="line"> * convenience base class for application objects, implementing this interface.</div><div class="line"> *</div><div class="line"> * &lt;p&gt;For a list of all bean lifecycle methods, see the</div><div class="line"> * &#123;@link org.springframework.beans.factory.BeanFactory BeanFactory javadocs&#125;.</div><div class="line"> *</div><div class="line"> * @author Rod Johnson</div><div class="line"> * @author Juergen Hoeller</div><div class="line"> * @author Chris Beams</div><div class="line"> * @see ResourceLoaderAware</div><div class="line"> * @see ApplicationEventPublisherAware</div><div class="line"> * @see MessageSourceAware</div><div class="line"> * @see org.springframework.context.support.ApplicationObjectSupport</div><div class="line"> * @see org.springframework.beans.factory.BeanFactoryAware</div><div class="line"> */</div><div class="line">public interface ApplicationContextAware extends Aware &#123;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * Set the ApplicationContext that this object runs in.</div><div class="line">	 * Normally this call will be used to initialize the object.</div><div class="line">	 * &lt;p&gt;Invoked after population of normal bean properties but before an init callback such</div><div class="line">	 * as &#123;@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()&#125;</div><div class="line">	 * or a custom init-method. Invoked after &#123;@link ResourceLoaderAware#setResourceLoader&#125;,</div><div class="line">	 * &#123;@link ApplicationEventPublisherAware#setApplicationEventPublisher&#125; and</div><div class="line">	 * &#123;@link MessageSourceAware&#125;, if applicable.</div><div class="line">	 * @param applicationContext the ApplicationContext object to be used by this object</div><div class="line">	 * @throws ApplicationContextException in case of context initialization errors</div><div class="line">	 * @throws BeansException if thrown by application context methods</div><div class="line">	 * @see org.springframework.beans.factory.BeanInitializationException</div><div class="line">	 */</div><div class="line">	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>从源码中可以看到,ApplicationContextAware接口只有一个方法setApplicationContext,实现了该接口的子类在spring容器启动初始化的时候获取
上下文信息ApplicationContext，通过ApplicationContext可以获取Spring容器内的很多信息(比如获取所有已经注册到spring容器的bean)
</code></pre><h5 id="二、创建maven项目-amp-添加基本依赖"><a href="#二、创建maven项目-amp-添加基本依赖" class="headerlink" title="二、创建maven项目&amp;添加基本依赖"></a>二、创建maven项目&amp;添加基本依赖</h5><pre><code>创建简单的maven项目并添加一下依赖:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">&lt;!-- spring-beans依赖 --&gt;		</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-beans&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- spring-context依赖 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-context&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-context-support&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div></pre></td></tr></table></figure>
<h5 id="三、编写上下文工具类并注册到spring容器"><a href="#三、编写上下文工具类并注册到spring容器" class="headerlink" title="三、编写上下文工具类并注册到spring容器"></a>三、编写上下文工具类并注册到spring容器</h5><p><em>1.首先我们编写上下文操作的工具类:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.demo1.util;</div><div class="line"></div><div class="line">import org.springframework.beans.BeansException;</div><div class="line">import org.springframework.context.ApplicationContext;</div><div class="line">import org.springframework.context.ApplicationContextAware;</div><div class="line"></div><div class="line">import java.util.Map;</div><div class="line"></div><div class="line"></div><div class="line">/**</div><div class="line"> * spring上下文工具类</div><div class="line"> * &lt;p&gt;可以使用该类获取spring的信息(比如所有已经注册到spring容器的bean)&lt;/p&gt;</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-08-28 16:30 Monday</div><div class="line"> * @since V1.3.1</div><div class="line"> */</div><div class="line">public class SpringContextUtil implements ApplicationContextAware &#123;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 将applicationContext设置成静态属性,一次初始化后就任何地方就可以使用</div><div class="line">     */</div><div class="line">    private static ApplicationContext applicationContext;</div><div class="line">    </div><div class="line"></div><div class="line">	/* </div><div class="line">	 * 该方法在spring初始化该bean的时候触发,触发之后该类的静态属性ApplicationContext就获得了spring的上下文信息</div><div class="line">	 * </div><div class="line">	 * (non-Javadoc)</div><div class="line">	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)</div><div class="line">	 */</div><div class="line">	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException &#123;</div><div class="line">		SpringContextUtil.applicationContext = applicationContext;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 获取spring上下文信息</div><div class="line">     * </div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static ApplicationContext getApplicationContext() &#123;</div><div class="line">        checkApplicationContext();</div><div class="line">        return applicationContext;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 根据名称获取bean</div><div class="line">     * </div><div class="line">     * @param name</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static &lt;T&gt; T getBean(String name) &#123;</div><div class="line">        checkApplicationContext();</div><div class="line">        return (T) applicationContext.getBean(name);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 根据类型获取bean(如果一个接口有多个实现这种方式获取会有问题)</div><div class="line">     * </div><div class="line">     * @param requiredType</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static &lt;T&gt; T getBean(Class&lt;T&gt; requiredType) &#123;</div><div class="line">        checkApplicationContext();</div><div class="line">        return applicationContext.getBean(requiredType);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 检查是否包含name对应的bean</div><div class="line">     * </div><div class="line">     * @param name</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static boolean containsBean(String name) &#123;</div><div class="line">        checkApplicationContext();</div><div class="line">        return applicationContext.containsBean(name);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 获取对应类型的所有bean列表</div><div class="line">     * </div><div class="line">     * @param requiredType</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static &lt;T&gt; Map&lt;String, T&gt; getBeans(Class&lt;T&gt; requiredType) &#123;</div><div class="line">        checkApplicationContext();</div><div class="line">        return applicationContext.getBeansOfType(requiredType);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    /**</div><div class="line">     * 根据名称和类型获取bean</div><div class="line">     * @author Typhoon</div><div class="line">     * @param name</div><div class="line">     * @param clazz</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    public static &lt;T&gt; T getBean(String name,Class&lt;T&gt; clazz) &#123;</div><div class="line">    	checkApplicationContext();</div><div class="line">    	return applicationContext.getBean(name, clazz);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 清空上下文信息</div><div class="line">     */</div><div class="line">    public static void cleanApplicationContext() &#123;</div><div class="line">        applicationContext = null;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 检查上下文是否注册成功</div><div class="line">     */</div><div class="line">    private static void checkApplicationContext() &#123;</div><div class="line">        if (applicationContext == null)</div><div class="line">            throw new IllegalStateException(&quot;applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil&quot;);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<pre><code>代码中最重要的一个方法就是对ApplicationContextAware的实现,通过此方法我们直接将spring上下文信息赋值给该工具类的静态属性。
上述的工具类提供了一些常用的操作方法,如果不能满足你的需求可以自己做扩展.
</code></pre><p><em>2.将工具类注册到spring容器:</em><br>    在src/main/resource目录下创建spring.xml并添加如下配置:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</div><div class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;  </div><div class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; </div><div class="line">    xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;  </div><div class="line">    xmlns:p=&quot;http://www.springframework.org/schema/p&quot;  </div><div class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot; </div><div class="line">    xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;</div><div class="line">    xmlns:task=&quot;http://www.springframework.org/schema/task&quot;</div><div class="line">    xsi:schemaLocation=&quot;    </div><div class="line">        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    </div><div class="line">        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  </div><div class="line">        http://www.springframework.org/schema/context     </div><div class="line">        http://www.springframework.org/schema/context/spring-context-3.1.xsd</div><div class="line">        http://www.springframework.org/schema/task    </div><div class="line">        http://www.springframework.org/schema/task/spring-task-3.1.xsd </div><div class="line">        http://www.springframework.org/schema/tx </div><div class="line">        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd&quot;&gt;</div><div class="line">    </div><div class="line">    &lt;bean class=&quot;com.typhoon.demo1.util.SpringContextUtil&quot; /&gt;</div><div class="line">&lt;/beans&gt;</div></pre></td></tr></table></figure></p>
<h5 id="四、编写供上下文工具类操作的bean并注入spring容器"><a href="#四、编写供上下文工具类操作的bean并注入spring容器" class="headerlink" title="四、编写供上下文工具类操作的bean并注入spring容器"></a>四、编写供上下文工具类操作的bean并注入spring容器</h5><p><em>1.编写接口</em><br>    编写一个简单的service接口:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.demo1.service;</div><div class="line"></div><div class="line">import com.typhoon.demo1.entity.User;</div><div class="line"></div><div class="line">public interface UserService &#123;</div><div class="line">	</div><div class="line">	User getById(Long id);</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><em>2.编写接口实现</em><br>    对上述service接口编写简单的实现类:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.demo1.service.impl;</div><div class="line"></div><div class="line">import com.typhoon.demo1.entity.User;</div><div class="line">import com.typhoon.demo1.service.UserService;</div><div class="line"></div><div class="line">public class UserServiceImpl implements UserService &#123;</div><div class="line"></div><div class="line">	public User getById(Long id) &#123;</div><div class="line">		User u = new User();</div><div class="line">		u.setId(1L);</div><div class="line">		u.setAge(27);</div><div class="line">		u.setName(&quot;typhoon&quot;);</div><div class="line">		return u;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><em>3.将service注册到spring容器中</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;bean id=&quot;userService&quot; class=&quot;com.typhoon.demo1.service.impl.UserServiceImpl&quot; /&gt;</div></pre></td></tr></table></figure></p>
<h5 id="五、编写单元测试"><a href="#五、编写单元测试" class="headerlink" title="五、编写单元测试"></a>五、编写单元测试</h5><pre><code>编写一个单元测试类当做消费方,并且运行观察结果:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.demo1.consumer;</div><div class="line"></div><div class="line">import java.util.Map;</div><div class="line"></div><div class="line">import org.apache.commons.lang3.builder.ToStringBuilder;</div><div class="line">import org.springframework.context.support.ClassPathXmlApplicationContext;</div><div class="line"></div><div class="line">import com.typhoon.demo1.service.UserService;</div><div class="line">import com.typhoon.demo1.util.SpringContextUtil;</div><div class="line"></div><div class="line">public class ApplicationContextConsumer &#123;</div><div class="line"></div><div class="line">	public static void main(String[] args) &#123;</div><div class="line">		new ClassPathXmlApplicationContext(&quot;spring.xml&quot;).start();</div><div class="line">		</div><div class="line">		UserService service1 = SpringContextUtil.getBean(UserService.class);</div><div class="line">		System.out.println(&quot;方式1结果:&quot; + ToStringBuilder.reflectionToString(service1.getById(1L)));</div><div class="line">		</div><div class="line">		UserService service2 = SpringContextUtil.getBean(&quot;userService&quot;);</div><div class="line">		System.out.println(&quot;方式2结果:&quot; + ToStringBuilder.reflectionToString(service2.getById(1L)));</div><div class="line">		</div><div class="line">		UserService service3 = SpringContextUtil.getBean(&quot;userService&quot;, UserService.class);</div><div class="line">		System.out.println(&quot;方式3结果:&quot; + ToStringBuilder.reflectionToString(service3.getById(1L)));</div><div class="line">		</div><div class="line">		Map&lt;String, UserService&gt; beans = SpringContextUtil.getBeans(UserService.class);</div><div class="line">		for(Map.Entry&lt;String, UserService&gt; entry : beans.entrySet()) &#123;</div><div class="line">			System.out.println(entry.getKey() + &quot;:&quot; + entry.getValue());</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>运行后看到如下结果:
</code></pre><img src="/typhoon/2017/08/28/spring上下文工具类/1.png" alt="result" title="result">
<pre><code>可以看到通过上述运行结果,我们已经实现了通过上下文工具类操作spring容器中的bean.
</code></pre><h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><pre><code>通过上述一系列配置和编码,我们已经实现了通过上下文工具类一次注册处处可以使用获取spring信息,该工具类在我们编写
公共模块中需要操作db或者redis等第三方容器的时候特别方便,或者说不需要繁杂的spring配置的时候也可以使用
</code></pre><p><em>ps</em>:原创不易，多多支持!</p>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/spring/">spring</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/spring上下文工具类/">spring上下文工具类</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2017/08/28/spring上下文工具类/" data-title="spring上下文工具类 | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2017/08/29/spring-redis缓存注解/" title="spring+redis缓存注解">
  <strong>上一篇：</strong><br/>
  <span>
  spring+redis缓存注解</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2017/08/28/使用本地缓存/"  title="使用本地缓存">
 <strong>下一篇：</strong><br/> 
 <span>使用本地缓存
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、概念描述"><span class="toc-number">1.</span> <span class="toc-text">一、概念描述</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、创建maven项目-amp-添加基本依赖"><span class="toc-number">2.</span> <span class="toc-text">二、创建maven项目&添加基本依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写上下文工具类并注册到spring容器"><span class="toc-number">3.</span> <span class="toc-text">三、编写上下文工具类并注册到spring容器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、编写供上下文工具类操作的bean并注入spring容器"><span class="toc-number">4.</span> <span class="toc-text">四、编写供上下文工具类操作的bean并注入spring容器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#五、编写单元测试"><span class="toc-number">5.</span> <span class="toc-text">五、编写单元测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
